<?php
namespace app\api\controller;

use app\api\model\Coupon as CouponModel;
use app\api\model\MemberCoupon;
use think\Request;

/**
 * 优惠券API控制器
 * Class Coupon
 * @package app\api\controller
 */
class Coupon extends BaseController
{
    /**
     * 获取用户优惠券列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function getUserCoupons(Request $request)
    {
        if (!$this->checkToken()) {
            return false;
        }
        
        // 获取请求参数
        $status = $request->param('status', 'all'); // 优惠券状态：all-全部，unused-未使用，used-已使用，expired-已过期
        
        // 查询条件
        $where = [
            'member_id' => $this->userId,
        ];
        
        // 根据状态筛选
        if ($status !== 'all') {
            switch ($status) {
                case 'unused':
                    $where['is_used'] = 0;
                    $where['expire_time'] = ['>=', time()];
                    break;
                case 'used':
                    $where['is_used'] = 1;
                    break;
                case 'expired':
                    $where['is_used'] = 0;
                    $where['expire_time'] = ['<', time()];
                    break;
            }
        }
        
        // 查询用户优惠券列表
        $list = MemberCoupon::alias('mc')
            ->join('park_coupon c', 'mc.coupon_id = c.id')
            ->where($where)
            ->field('mc.id, mc.coupon_id, c.name, c.amount, c.min_price, c.start_time, mc.expire_time, mc.is_used, mc.use_time')
            ->order(['mc.expire_time' => 'asc'])
            ->select();
            
        // 处理数据
        foreach ($list as &$item) {
            $item['start_time_text'] = date('Y-m-d', $item['start_time']);
            $item['expire_time_text'] = date('Y-m-d', $item['expire_time']);
            $item['use_time_text'] = $item['use_time'] ? date('Y-m-d H:i:s', $item['use_time']) : '';
            
            // 判断优惠券状态
            if ($item['is_used'] == 1) {
                $item['status'] = 'used';
                $item['status_text'] = '已使用';
            } else if ($item['expire_time'] < time()) {
                $item['status'] = 'expired';
                $item['status_text'] = '已过期';
            } else {
                $item['status'] = 'unused';
                $item['status_text'] = '未使用';
            }
        }
        
        return $this->renderSuccess('获取成功', $list);
    }
    
    /**
     * 使用优惠券
     * @param Request $request
     * @return \think\response\Json
     */
    public function useCoupon(Request $request)
    {
        if (!$this->checkToken()) {
            return false;
        }
        
        // 获取请求参数
        $couponId = $request->post('coupon_id');
        $orderId = $request->post('order_id');
        
        if (empty($couponId) || empty($orderId)) {
            return $this->renderError('参数错误：缺少必要参数');
        }
        
        // 查询优惠券信息
        $memberCoupon = MemberCoupon::where([
            'id' => $couponId,
            'member_id' => $this->userId,
            'is_used' => 0
        ])->find();
        
        if (!$memberCoupon) {
            return $this->renderError('优惠券不存在或已使用');
        }
        
        // 检查优惠券是否过期
        if ($memberCoupon['expire_time'] < time()) {
            return $this->renderError('优惠券已过期');
        }
        
        // 查询订单信息
        $order = \app\api\model\Order::where([
            'id' => $orderId,
            'member_id' => $this->userId,
            'status' => 0 // 未支付
        ])->find();
        
        if (!$order) {
            return $this->renderError('订单不存在或状态错误');
        }
        
        // 获取优惠券详情
        $coupon = CouponModel::get($memberCoupon['coupon_id']);
        
        // 检查订单金额是否满足优惠券使用条件
        if ($order['amount'] < $coupon['min_price']) {
            return $this->renderError('订单金额不满足优惠券使用条件');
        }
        
        // 更新订单信息
        $newAmount = $order['amount'] - $coupon['amount'];
        $newAmount = $newAmount > 0 ? $newAmount : 0.01; // 确保订单金额不小于0.01元
        
        $order->save([
            'coupon_id' => $couponId,
            'coupon_amount' => $coupon['amount'],
            'amount' => $newAmount
        ]);
        
        // 更新优惠券状态
        $memberCoupon->save([
            'is_used' => 1,
            'use_time' => time(),
            'order_id' => $orderId
        ]);
        
        return $this->renderSuccess('优惠券使用成功', [
            'order_id' => $order['id'],
            'original_amount' => $order['amount'] + $coupon['amount'],
            'coupon_amount' => $coupon['amount'],
            'amount' => $order['amount']
        ]);
    }
} 